<template>
  <view class="min-h-screen bg-[#f5f5f5] pb-[100rpx]">
    <!-- 顶部用户信息 -->
    <view
      class="relative px-[30rpx] h-[calc(477rpx-88rpx)]  bg-[url('@/static/my/my_bgc.png')] bg-no-repeat bg-center bg-cover pt-[64rpx]"
    >
      <div class="flex items-center ">
        <img
          class="w-[128rpx] h-[128rpx] rounded-full mr-[20rpx]"
          :src='userInfo.avatar?userInfo.avatar:"/static/my/default-avatar.png"'
          mode="aspectFill"
        ></img>
        <text
          class="color-[#121836] font-bold text-[36rpx] "
          @click="goToLogin"
          > {{userInfo.userName ? userInfo.userName : '点击登录/注册'}} </text
        > 
      </div>
      <!-- 会员中心卡片 -->
      <view
        class="Membershipcard absolute bottom-0 left-0 ml-[30rpx] mr-[30rpx] right-0 h-[156rpx] flex justify-between items-center px-[40rpx] text-white"
      >
        <view class="flex items-center">
          <image
            class="w-[100rpx] h-[100rpx] mr-[27rpx]"
            src="/static/my/crown.png"
          ></image>
          <view class="flex flex-col">
            <text class="text-[32rpx] text-[#E3C377]">会员中心</text>
            <text class="text-[24rpx] text-[#E3C377] mt-[10rpx]" @click="handlePoints">积分: {{userInfo.integral}} ></text>
          </view>
        </view>
        <view class="flex flex-col items-center">
          <image
            class="w-[50rpx] h-[50rpx] mb-[10rpx]"
            src="/static/my/diamond.png"
          ></image>
          <text class="text-[28rpx] text-[#E3C377]">会员权益</text>
        </view>
      </view>
    </view>

    <!-- 项目统计区域 -->
    <view class="card">
      <view class="flex py-[20rpx]  border-b border-[#eee]">
        <text class="flex-1 text-center text-[32rpx] text-[#121836] font-medium"
          >我的项目</text
        >
        <text class="flex-1 text-center text-[32rpx] text-[#121836] font-medium"
          >总次数</text
        >
        <text class="flex-1 text-center text-[32rpx] text-[#121836] font-medium"
          >剩余次数</text
        >
      </view>

      <!-- 项目列表 -->
      <view>
        <view
          class="flex py-[20rpx]"
          v-for="(item, index) in displayedProjects"
          :key="index"
        >
          <text class="flex-1 text-center text-[30rpx] text-[#121836]">{{
            item.projectName
          }}</text>
          <text class="flex-1 text-center text-[30rpx] text-[#121836]">{{
            item.totalSessions
          }}</text>
          <text class="flex-1 text-center text-[30rpx] text-[#121836]">{{
            item.remainingSessions
          }}</text>
        </view>
        <!-- 添加空状态组件 -->
        <up-empty
          v-if="projectList.length === 0"
          mode="list" 
          text="暂无项目数据"
          marginTop="30"
        ></up-empty>
      </view>

      <!-- 全部项目 -->
      <view
        class="flex flex-col justify-center items-center py-[20rpx] border-t border-[#eee]"
        @click="toggleAllProjects"
        v-if="projectList.length > 2"
      >
        <text class="text-[26rpx] text-[#AF6C31] ">{{showAllProjects ? '收起' : '全部项目'}}</text>
        <image
          class="w-[48rpx] h-[48rpx] transition-transform duration-300"
          :class="{ 'rotate-180': showAllProjects }"
          src="/static/my/arrow-down.png"
        ></image>
      </view>
    </view>

    <!-- 订单管理卡片 -->
    <view class="card py-[30rpx] px-[32rpx]">
      <view class="w-full flex justify-between items-center mb-[30rpx]">
        <view class="section-title">我的订单</view>
        <view class="more-link" @click="handleOrder">查看全部 ></view>
      </view>
      <view class="flex justify-between">
        <view class="flex flex-col items-center" @click="handleOrderType('all')">
          <view class="count-num">{{orderCount.all || 0}}</view>
          <view class="count-label">全部</view>
        </view>
        <view class="flex flex-col items-center" @click="handleOrderType('unfinished')">
          <view class="count-num">{{orderCount.unfinished || 0}}</view>
          <view class="count-label">待核销</view>
        </view>
        <view class="flex flex-col items-center" @click="handleOrderType('finished')">
          <view class="count-num">{{orderCount.finished || 0}}</view>
          <view class="count-label">已完成</view>
        </view>
        <view class="flex flex-col items-center" @click="handleOrderType('cancelled')">
          <view class="count-num">{{orderCount.cancelled || 0}}</view>
          <view class="count-label">已取消</view>
        </view>
      </view>
    </view>

    <!-- 预约项目卡片 -->
    <view
      class="card appointment-card flex justify-between p-[30rpx]"
      v-if="appointment"  
    >
      <view class="w-full">
        <view class="w-full flex justify-between items-center mb-[30rpx]">
          <view class="section-title">我的预约项目</view>
          <view class="more-link" @click="handleProject">查看全部 ></view>
        </view>
     <view class="flex justify-between"> 
         <view class="flex flex-col">
            <view class="flex items-center mb-[8rpx]">
              <text class=" text-[26rpx] text-[#121836] font-medium">项目：</text>
              <text class="flex-1 text-sm text-[#585766]">{{ appointment.projectName }}</text>
            </view>
            <view class="flex items-center mb-[8rpx]">
              <text class=" text-[26rpx] text-[#121836] font-medium">医师：</text>
              <text class="flex-1 text-sm text-[#585766]">{{ appointment.doctorName }}</text>
            </view>
            <view class="flex items-center">
              <text class=" text-[26rpx] text-[#121836] font-medium">时间：</text>
              <text class="flex-1 text-sm text-[#585766]">{{ 
                appointment.appointmentDate?.split(" ")[0] + ' ' + appointment.appointmentTime 
              }}</text>
            </view>
        </view>
        <QRCode 
          :url="qrCodeUrl ?? 'https://www.baidu.com'" 
          :size="96" 
           background="#fff"
            foreground="#000"
        />

   
       </view>
      </view>
    </view>
    <!-- 添加预约为空的情况 -->
    <view class="card p-[30rpx]" v-else>
      <up-empty
        mode="order"
        text="暂无预约项目"
        marginTop="20"
      ></up-empty>
    </view>

    <!-- 其他服务 -->
    <view class="card py-[30rpx] px-[32rpx]">
      <text class="section-title mb-[30rpx] block"
        >其他服务</text
      >
      <view class="flex justify-around">
        <view class="flex flex-col items-center" @click="handleService('faq')">
          <image
            class="service-icon"
            src="/static/my/question.png"
          ></image>
          <text class="service-text">问题与建议</text>
        </view>
        <view
          class="flex flex-col items-center"
          @click="handleService('contact')"
        >
          <image
            class="service-icon"
            src="/static/my/contact.png"
          ></image>
          <text class="service-text">联系我们</text>
        </view>
        <view
          class="flex flex-col items-center"
          @click="handleService('logout')"
        >
          <image
            class="service-icon"
            src="/static/my/logout.png"
          ></image>
          <text class="service-text">退出登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { getQrCodeUrl, getUserInfo } from '@/api'
import type { MyProjectResponseData, MyProjectAppointmentsResponseData, recordResponse } from '@/api/my'
import { getMyProject, getMyProjectAppointments } from '@/api/my'
import { getOrderCount } from '@/api/shop'
import QRCode from '@/components/qrCode/index.vue';
import { onShow } from "@dcloudio/uni-app";
// 用户信息
const userInfo = reactive({
  avatar: "",
  userName: "",
  memberId: "",
  integral: 0, // 添加积分字段
});
const qrCodeUrl = ref('')
// 项目列表
const projectList = ref<MyProjectResponseData[]>([
]);

// 是否显示全部项目
const showAllProjects = ref(false);

// 计算属性：根据showAllProjects返回要显示的项目列表
const displayedProjects = computed(() => {
  if (showAllProjects.value || projectList.value.length <= 2) {
    return projectList.value;
  } else {
    return projectList.value.slice(0, 2);
  }
});

// 订单数量
const orderCount = reactive({
  all: 0,
  unfinished: 0,
  finished: 0,
  cancelled: 0
});

onShow(async() => {
 const userInfo = uni.getStorageSync("userInfo");
  if (userInfo) {
    handelGetUserInfo(userInfo.id)
  }
  handleGetQrCodeUrl()
  await handleGetMyProject()
  await handelGetMyProjectAppointments()
  await handleGetOrderCount() // 新增：获取订单数量
})

// 获取二维码、
const handleGetQrCodeUrl = () => {
  getQrCodeUrl().then((res) => {
    qrCodeUrl.value = res.data
  })
}

// 获取我的项目
 const handleGetMyProject = () => {
  getMyProject().then((res) => {
    projectList.value = res.data;
  })
 }
 const pageNumber = ref(1)
 const pageSize = ref(10)
const handelGetMyProjectAppointments = () => {
  getMyProjectAppointments({
    pageNumber: pageNumber.value,
    pageSize: pageSize.value,
    type:1
  }).then((res) => {
    appointment.value = res.data.records[0]
    ;
  })
}
// 获取订单数量
const handleGetOrderCount = () => {
  getOrderCount().then((res: any) => {
    if (res.code === 200) {
      orderCount.all = res.data.totalCount || 0;
      orderCount.unfinished = res.data.pendingCount || 0;
      orderCount.finished = res.data.verifiedCount || 0;
      orderCount.cancelled = res.data.cancelledCount || 0;
    }
  }).catch((err: any) => {
    console.error('获取订单数量失败', err);
  });
}

// 根据id查询信息
const handelGetUserInfo = (id: any) => {
  getUserInfo(id).then((res) => {
    console.log(res);
    userInfo.avatar = res.data.userAvatar || '';
    userInfo.userName = res.data.userName || '';
    userInfo.integral = res.data.integral || 0; // 获取积分
  });
}

// 预约信息
const appointment = ref<recordResponse>({
  orderId: 0,
  projectId: 0,
  projectName: "",
  doctorId: 0,
  doctorName: "",
  appointmentDate: "",
  appointmentTime: "",
  projectImage: "",
  qrCodeUrl: '',
  totalSessions: 0,
  remainingSessions: 0
});

// 跳转到登录页面
const goToLogin = () => {
  if(!userInfo.userName){
    uni.navigateTo({
      url: "/pages/login/index",
    });
  }
};

// 切换显示全部项目
const toggleAllProjects = () => {
  showAllProjects.value = !showAllProjects.value;

};
const handleProject = () => {
   uni.navigateTo({
    url: "/pages/my/appointments",
   })
}

// 跳转到积分页面
const handlePoints = () => {
  uni.navigateTo({
    url: "/pages/my/points",
  });
}
// 跳转到订单页面
const handleOrder = () => {
  uni.navigateTo({
    url: "/pages/my/order",
  });
}

// 处理不同类型的订单
const handleOrderType = (type: string) => {
  uni.navigateTo({
    url: `/pages/my/order?type=${type}`,
  });
}

// 处理服务点击
const handleService = (type: string) => {
  switch (type) {
    case "faq":
      uni.navigateTo({ url: "/pages/public/problemSugges" });
      break;
    case "contact":
      uni.navigateTo({ url: "/pages/public/contact" });
      break;
    case "logout":
      uni.showModal({
        title: "提示",
        content: "确定要退出登录吗？",
        success: (res) => {
          if (res.confirm) {
            uni.showToast({ title: "已退出登录",   icon: "none", });
            uni.navigateTo({ url: "/pages/login/index" });
          }
        },
      });
      break;
  }
};

// 切换标签页
const switchTab = (tab: string) => {
  uni.switchTab({
    url: `/pages/${tab}/index`,
  });
};
</script>

<style>
/* TailwindCSS已经替代了所有样式 */
.Membershipcard{
  background: url('@/static/my/Membershipcard.png') no-repeat ;
  background-size: 100% 100%;
}

/* 统一卡片样式 */
.card {
  margin: 30rpx;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

/* 统一标题样式 */
.section-title {
  font-size: 32rpx;
  color: #121836;
  font-weight: bold;
  padding-left: 10rpx;
}

/* 统一"更多"链接样式 */
.more-link {
  font-size: 24rpx;
  color: #AF6C31;
}

/* 统一计数样式 */
.count-num {
  font-size: 32rpx;
  color: #121836;
  font-weight: medium;
  margin-bottom: 10rpx;
}

.count-label {
  font-size: 26rpx;
  color: #585766;
}

/* 预约卡片特殊背景 */
.appointment-card {
  background: linear-gradient(to right, #FDEAD3, #FAEFE3);
}

/* 服务图标统一样式 */
.service-icon {
  width: 42rpx;
  height: 42rpx;
  margin-bottom: 22rpx;
}

.service-text {
  font-size: 26rpx;
  color: #121836;
}
</style>
